package com.xiong.wuliao.HomeIntelligent;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Created by asus on 2017/1/18.
 */
public class HttpUtil {
    private static final String URL = "http://www.tuling123.com/openapi/api";
    private static final String API_KEY = "f0e24c1b19504a37a3c77a64bc288536";

    /**
     * 发送一个消息，得到返回的消息实体deader258
     * @param msg
     * @return
     */
    public static ChatMessage sendMessage(String msg){
        ChatMessage chatMessage = new ChatMessage();
        String jsonRes = doGet(msg);
        Gson gson = new Gson();
        Result result = null;
        try {
            result = gson.fromJson(jsonRes, Result.class);
            chatMessage.setMsg(result.getText());
        } catch (JsonSyntaxException e) {
            chatMessage.setMsg("对不起哦，我大脑反应不过来了...");
        }
        chatMessage.setDate(new Date());
        chatMessage.setType(ChatMessage.Type.INCOMING);

        return chatMessage;
    }

    public static String doGet(String msg) {
        String result = "";
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        String url = setParams(msg);
        try {
            java.net.URL urlNet = new java.net.URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlNet.openConnection();
            connection.setReadTimeout(5*1000);
            connection.setConnectTimeout(5*1000);
            connection.setRequestMethod("GET");

            is = connection.getInputStream();
            int len = -1;
            byte[] buf = new byte[128];
            bos = new ByteArrayOutputStream();

            while ((len = is.read(buf)) != -1){
                bos.write(buf,0,len);
            }
            bos.flush();
            result = new String(bos.toByteArray());
        }catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    private static String setParams(String msg) {
        String url = "";
        try {
            url = URL + "?key=" + API_KEY + "&info=" + URLEncoder.encode(msg,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }
}
